/**
 *	Plug in pour Streamer simplement des messages
 *	@author	Artiom FEDOROV
 */
  
(function($) {

	$.fn.simpleStreamer=function() {

		var lastTimestamp=0;
		var apiPath = "json.php";
		var timeStep = 1000;

		var tplMain;
		var tplViewItem;
		var tplViewEdit;
	
		var content;
		var editContent;
		var nbrItems = 3;
		var lastItem = {};
		var action;
		var controller;

		var canAdd = false;


		/**
		 *	Methode principale qui parcours tous les éléments
		 *	qui se sont vu accrocher le plug in
		 */

		return this.each(function() {
			
			action =  $(this).data("action");
			controller = $(this).data("controller"); 
			nbrItems_tmp =  $(this).data("nbritems");
			
			if (nbrItems_tmp !== undefined) {
				nbrItems = nbrItems_tmp;
			}
			
			canAdd_tmp =  $(this).data("canadd");
			
			if (canAdd_tmp !== undefined) {
				canAdd = canAdd_tmp;
			}

			ping_tmp =  $(this).data("ping");
			
			if (ping_tmp !== undefined) {
				timeStep = ping_tmp;
			}
			
			
			if (action == "") {
				action="index";
			}
			
			console.log("Action : " + action);
			buildScafold(this);
			loadContent();
		});
				
			
		/** 
		 *	Methode qui construit le composant en html,
		 *	qui charge tous les templates
		 *	main, viewItem, viewEdit
		 *
		 **/
		
		function buildScafold(dom) {

			tplMain = $(dom).find('.main').html();
			tplViewItem = $(dom).find('.viewItem').html();
			tplViewEdit = $(dom).find('.editItem').html();
			tplListItems =  $(dom).find('.listItems').html();
			
			Mustache.parse(tplMain);
			Mustache.parse(tplViewItem);
			Mustache.parse(tplViewEdit);
			Mustache.parse(tplListItems);

			var rendered = Mustache.render(tplMain);
			$(dom).html(rendered);	
			content = $(dom).find('.appendable');
			
			if (canAdd) {
				var renderedEdit = Mustache.render(tplViewEdit);
				editContent = $(dom).find('.editZone');
				editContent.html(renderedEdit);
				addEditAction();
			}
				
		}
		
		
		function addEditAction() {
			
			var form = editContent.find("form");
			form.submit(function( event ) {
					//console.log( $( this ).serializeArray() );
					event.preventDefault();
					
					var data = $(this).serializeArray();
					var size = data.length;

					var message = {};					
					for (index = 0; index < size; ++index) {
						var varname = data[index].name;
						message[varname] = data[index].value
					}
					
					console.log( message );
					
					var submit = true;
					
					// Reinit Form
					editContent.find("input").each(function() {
					
						var sticky = $(this).data('stickydata');
						var required = $(this).data('required');
						
						
						if (required == true) {
							var curval = $(this).val();
							if (curval == "") {
								submit = false;
								$(this).addClass("alert-danger");
							} else {
								$(this).removeClass("alert-danger");
							}
						}
						
						if (sticky != true) {
							$(this).val("");
						}
						
					});
					
					if (submit) {
						$.post(apiPath + '?action=add' + '&controller=' + controller, message)
						.done(function( data ) {
						});			
					}
					
						
				});
			
			
		}
		
		
		
		
		/**
		 *	Méthode qui se charge de charger le contenu la premiere fois
		 *	Puis maintient les mises a jour de la liste
		 *	C'est aussi cette méthode qui lance le timeOut pour des maj regulieres
		 */
		
		function loadContent() {
			
			$.getJSON(apiPath + '?action=' + action + '&controller=' + controller + '&nbritems=' + nbrItems, lastItem, function(data) {
				//console.log(data);
				var rendered = "";
				var size = data.length;
				for (index = 0; index < size; ++index) {
					console.log(data[index]);	
					rendered += Mustache.render(tplViewItem, data[index]);
					// On garde en mémoire le dernier élement
					if (index == 0) {
						lastItem = data[index];

					}
				}

				content.prepend(rendered);													
				removeOverflowContent();
				
				 setTimeout(function(){ 
					loadContent();
				 }, timeStep);
			});
		}
		
		
		function removeOverflowContent() {

			var curentCount = content.children().length;
			
			// Bloc qui se charge de remover les itemps en trop		
			if (curentCount > nbrItems) {
				var nbrToRemove = curentCount - nbrItems;
				for (i = 0; i < nbrToRemove; ++i) {
					content.children().last().remove();
				}
			}
		}
	};
})(jQuery);
